package com.caishi.lkx.common;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.caishi.lkx.common.config.DiamondConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class PushService {

    public enum PushType {
        // 离线推送
        push,
        // 在线推送
        online,
        // 心跳
        heart,
    }


    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private DiamondConfig diamondConfig;

    /**
     * <p>
     * <h3>作者 keray</h3>
     * <h3>时间： 2021/6/9 9:52 上午</h3>
     * 同步推送消息
     * </p>
     *
     * @param pushUid     推送uid
     * @param json        消息内容 文本
     * @param messageType 消息类型 push 支持离线推送消息 | online 仅在线推送
     * @param channel     消息通道 0 uid | 1 group | 2 service
     * @throws Exception
     */
    public void syncPushMessage(String pushUid, String json, PushType messageType, int channel) throws Exception {
        try {
            HttpUtil.post(StrUtil.format("{}/web-push/server/message/push", diamondConfig.getWebPushDomain()),
                    objectMapper.writeValueAsString(MapUtil.builder()
                            .put("service", diamondConfig.getWebPushService())
                            .put("targetId", pushUid)
                            .put("channel", channel)
                            .put("type", messageType.name())
                            .put("message", json)
                            .put("version", 1)
                            .put("async", true)
                            .put("save", false)
                            .build()));
        } catch (Exception e) {
            log.error("消息推送失败", e);
            throw e;
        }
    }

    /**
     * @param duid        浏览器uuid
     * @param type
     * @param data
     * @param messageType
     * @param channel
     * @throws Exception
     */
    public void sendProjectMessage(String duid, String type, Object data, PushType messageType, int channel) throws Exception {
        syncPushMessage(duid, JSON.toJSONString(MapUtil.builder()
                .put("type", type)
                .put("data", data)
                .build()), messageType, channel);
    }

}
